package Forms;

import Classes.MInterface;
import Classes.SumSubject;
import Classes.SummerSy;
import Classes.User;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Owner
 */
public class OpenSumSY extends javax.swing.JFrame {
    static MInterface mi;
    static User cUser;
    
    ArrayList<SumSubject> ssList;
    ArrayList<SumSubject> sumList = new ArrayList<SumSubject>();
    DefaultTableModel dtm;
    SumSubject sSub;

    /**
     * Creates new form CurriculumSchoolYear
     */
    public OpenSumSY(User user, MInterface i) {
        initComponents();
        mi = i;
        
        try {
            int year;
            int y = mi.getToday();
            year = y;
            
            for (int x = year - 5; x < year + 100; x++) {
                syCb.addItem("Summer " + x);
            }
            
            dtm = new DefaultTableModel(new Object[] {sumTbl.getColumnName(0)}, 0);
            sumTbl.setModel(dtm);
            
            ssList = (ArrayList<SumSubject>) mi.SSList().clone();
            ArrayList<SumSubject> ss = new ArrayList<SumSubject>();
            for(int x = 0; x < ssList.size(); x++) {
                ss.add((SumSubject) ssList.get(x));
            }
            
            String subN = null;
            for(int x = 0; x < ss.size(); x++) {
                subN = ss.get(x).getSumSub();
                subCb.addItem(subN);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        syCb = new javax.swing.JComboBox();
        numFld = new javax.swing.JTextField();
        startChooser = new com.toedter.calendar.JDateChooser();
        endChooser = new com.toedter.calendar.JDateChooser();
        nxtBtn = new javax.swing.JButton();
        subCb = new javax.swing.JComboBox();
        jScrollPane3 = new javax.swing.JScrollPane();
        sumTbl = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        nxtBtn1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Open Summer School Year");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/banner.jpg"))); // NOI18N
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel2.setText("School Year:");

        jSeparator1.setForeground(new java.awt.Color(0, 102, 51));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel3.setText("Start Date:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel4.setText("End Date:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel5.setText("Subject:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel7.setText("Number of School Days:");

        syCb.setFont(new java.awt.Font("Tahoma", 0, 12));

        numFld.setFont(new java.awt.Font("Tahoma", 0, 12));
        numFld.setEnabled(false);

        startChooser.setDateFormatString("yy-MM-dd");
        startChooser.setFont(new java.awt.Font("Tahoma", 0, 12));

        endChooser.setDateFormatString("yy-MM-dd");
        endChooser.setFont(new java.awt.Font("Tahoma", 0, 12));

        nxtBtn.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        nxtBtn.setText("Cancel");
        nxtBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nxtBtnActionPerformed(evt);
            }
        });

        subCb.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        sumTbl.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Subjects for this School Year"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(sumTbl);

        jButton1.setText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        nxtBtn1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        nxtBtn1.setText("Save");
        nxtBtn1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nxtBtn1ActionPerformed(evt);
            }
        });

        jButton2.setText("Compute");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        btnAdd.setText("New Subject");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnRemove.setText("Remove");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(subCb, 0, 440, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(syCb, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(numFld, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2))
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 552, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jSeparator1))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemove)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 240, Short.MAX_VALUE)
                        .addComponent(nxtBtn1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nxtBtn))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(endChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
                            .addComponent(startChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(syCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(startChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(endChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(numFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(subCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nxtBtn)
                    .addComponent(nxtBtn1)
                    .addComponent(btnAdd)
                    .addComponent(btnRemove))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nxtBtn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nxtBtn1ActionPerformed
        String summer = syCb.getSelectedItem().toString();
        String start = ((JTextField)startChooser.getDateEditor().getUiComponent()).getText();
        String end = ((JTextField)endChooser.getDateEditor().getUiComponent()).getText();
        int num = Integer.valueOf(numFld.getText());
        
        try {
            if (start.isEmpty() || end.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Please fill out the needed fields", "Error", JOptionPane.ERROR_MESSAGE);
                jLabel3.setForeground(Color.red);
                jLabel4.setForeground(Color.red);
            } else if (startChooser.getDate().compareTo(endChooser.getDate()) > 0 || endChooser.getDate().compareTo(startChooser.getDate()) < 0) {
                JOptionPane.showMessageDialog(null, "Invalid Date", "Error", JOptionPane.ERROR_MESSAGE);
                jLabel3.setForeground(Color.red);
                jLabel4.setForeground(Color.red);
            } else if (numFld.getText().isEmpty()) {
                JOptionPane.showMessageDialog(null, "Please click compute button", "Error", JOptionPane.ERROR_MESSAGE);
                jLabel7.setForeground(Color.red);
            } else {   
                if(dtm.getRowCount() != 0) {
                    boolean add = false;
                    add = mi.add("add-summersy", new SummerSy(summer, start, end, num), "", cUser);  
                    ArrayList<Object> sn = new ArrayList<Object>();
                    for(int x = 0; x < dtm.getRowCount(); x++) {
                        sn.add(sumTbl.getValueAt(x, 0));
                    }
                    String b = mi.SumSubjectAdd(sn, syCb.getSelectedItem().toString());
                    JOptionPane.showMessageDialog(null, "School Year " + summer + " has been added", "Message", JOptionPane.INFORMATION_MESSAGE);
                    this.hide();           
                }else {
                    JOptionPane.showMessageDialog(null, "The Subject List does not contain anything", "Error", JOptionPane.ERROR_MESSAGE);                    
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_nxtBtn1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int schoolDays = 0;
        Calendar st = Calendar.getInstance();
        Calendar en = Calendar.getInstance();
                                        
        Date s = startChooser.getDate();
        Date e = endChooser.getDate();
                    
        st.setTime(s);
        en.setTime(e);
                    
        long milliseconds1 = st.getTimeInMillis();
        long milliseconds2 = en.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
                    
        long ans = diff / (24 * 60 * 60 * 1000);
                    
        do {
            st.add(Calendar.DAY_OF_MONTH, 1);
                if (st.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && st.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && en.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && en.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
                    schoolDays++;
                } 
         } while (st.getTimeInMillis() < en.getTimeInMillis());
            numFld.setText(String.valueOf(schoolDays));
    }//GEN-LAST:event_jButton2ActionPerformed

    private void nxtBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nxtBtnActionPerformed
        this.hide();
    }//GEN-LAST:event_nxtBtnActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        boolean p = false;
        try {
             
            SumSubject m = new SumSubject (JOptionPane.showInputDialog(null,"Enter the new Summer Subject"));
            if(m.getSumSub() != null) {
                 while(!p) {
                    if(m.getSumSub().length() == 0) {
                        JOptionPane.showMessageDialog(null, "Enter a subject name", "Error", JOptionPane.ERROR_MESSAGE);
                        p = false;
                    }else {           
                        String a = mi.SumSubAdd(m.getSumSub());                        
                        sumList.add(m);
                        dtm.addRow(new Object[] {m.getSumSub()}); 
//                        String a = mi.SumSubjectAdd(m, ssy);                    
                        JOptionPane.showMessageDialog(null, "Subject successfully added", "Subject Added", JOptionPane.INFORMATION_MESSAGE);
                        btnRemove.setEnabled(true);
                        p = true;
                    }                
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        // TODO add your handling code here:
        ssList.add(sumList.get(sumTbl.getSelectedRow()));
        jButton1.setEnabled(true);
        
        sumList.remove(sumTbl.getSelectedRow());
        dtm.removeRow(sumTbl.getSelectedRow());
        
        loadSubCB();
        if(sumTbl.getRowCount() == 0) {
            btnRemove.setEnabled(false);
        }
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        SumSubject ss = ssList.get(subCb.getSelectedIndex());
        
        sumList.add(ss);
        
        dtm.addRow(new Object[] {ss.getSumSub()});
        
        ssList.remove(ss);
        loadSubCB();
        btnRemove.setEnabled(true);
        
        if(subCb.getItemCount() == 0) {
            jButton1.setEnabled(false);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    public void loadSubCB() {
        subCb.removeAllItems();
        try {
            for(int x = 0; x < ssList.size(); x++) {
                subCb.addItem(ssList.get(x).getSumSub());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OpenSumSY.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OpenSumSY.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OpenSumSY.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OpenSumSY.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new OpenSumSY(cUser, mi).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnRemove;
    private com.toedter.calendar.JDateChooser endChooser;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField numFld;
    private javax.swing.JButton nxtBtn;
    private javax.swing.JButton nxtBtn1;
    private com.toedter.calendar.JDateChooser startChooser;
    private javax.swing.JComboBox subCb;
    private javax.swing.JTable sumTbl;
    private javax.swing.JComboBox syCb;
    // End of variables declaration//GEN-END:variables
}
